package com.witmore.skyline.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.witmore.skyline.db.entity.AreaRegionDO;
import com.witmore.skyline.db.mapper.AreaRegionMapper;
import com.witmore.skyline.web.service.RegionQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 地区查询服务实现
 *
 * @author 豆子高
 * @since 2025-10-22
 */
@Slf4j
@Service
public class RegionQueryServiceImpl implements RegionQueryService {

    @Autowired
    private AreaRegionMapper areaRegionMapper;

    @Override
    public RegionCodeInfo getRegionCodeByNames(String province, String city, String district) {
        // 参数校验：省市必传
        if (!StringUtils.hasText(province)) {
            throw new IllegalArgumentException("省份名称不能为空");
        }
        if (!StringUtils.hasText(city)) {
            throw new IllegalArgumentException("城市名称不能为空");
        }

        RegionCodeInfo result = new RegionCodeInfo();

        try {
            // 1. 查询省份信息（必须找到）
            AreaRegionDO provinceEntity = findRegionByName(province, 1);
            if (provinceEntity == null) {
                throw new IllegalArgumentException("找不到省份: " + province);
            }
            result.setProvCode(provinceEntity.getAdcode());
            result.setProvince(provinceEntity.getName());

            // 2. 在指定省份下查询城市信息（必须找到）
            AreaRegionDO cityEntity = findRegionByName(city, 2, provinceEntity.getAdcode());
            if (cityEntity == null) {
                throw new IllegalArgumentException("在省份[" + province + "]下找不到城市: " + city);
            }
            result.setCityCode(cityEntity.getAdcode());
            result.setCity(cityEntity.getName());

            // 3. 查询区县信息（可选）
            if (StringUtils.hasText(district)) {
                AreaRegionDO districtEntity = findRegionByName(district, 3, cityEntity.getAdcode());
                if (districtEntity == null) {
                    throw new IllegalArgumentException("在城市[" + city + "]下找不到区县: " + district);
                }
                result.setDistrictCode(districtEntity.getAdcode());
                result.setDistrict(districtEntity.getName());
            }

            // 4. 构建完整名称
            StringBuilder fullName = new StringBuilder();
            fullName.append(result.getProvince());
            // 对于直辖市，市级名称可能和省级相同，避免重复
            if (!result.getCity().equals(result.getProvince())) {
                fullName.append(result.getCity());
            }
            if (result.getDistrict() != null) {
                fullName.append(result.getDistrict());
            }
            result.setFullName(fullName.toString());

            return result;

        } catch (Exception e) {
            log.error("根据名称查询地区编码失败: 省={}, 市={}, 区={}", province, city, district, e);
            throw e;
        }
    }


    /**
     * 根据名称和级别查找地区
     *
     * @param name       地区名称
     * @param level      行政级别
     * @param parentCode 父级编码（可选，用于精确匹配）
     * @return 地区信息
     */
    private AreaRegionDO findRegionByName(String name, int level, String parentCode) {
        if (!StringUtils.hasText(name)) {
            return null;
        }

        // 从数据库查询
        LambdaQueryWrapper<AreaRegionDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AreaRegionDO::getLevel, level)
               .eq(AreaRegionDO::getIsActive, true);
        
        // 先尝试精确匹配
        wrapper.eq(AreaRegionDO::getName, name);

        // 添加父级编码条件
        if (parentCode != null) {
            if (level == 2) {
                wrapper.eq(AreaRegionDO::getProvCode, parentCode);
            } else if (level == 3) {
                wrapper.eq(AreaRegionDO::getCityCode, parentCode);
            }
        }

        List<AreaRegionDO> regions = areaRegionMapper.selectList(wrapper);
        
        if (!regions.isEmpty()) {
            return regions.get(0);  // 精确匹配，直接返回第一个
        }
        
        // 如果精确匹配失败，尝试简称匹配
        String shortName = getShortName(name);
        if (!shortName.equals(name)) {
            wrapper.clear();
            wrapper.eq(AreaRegionDO::getLevel, level)
                   .eq(AreaRegionDO::getIsActive, true)
                   .eq(AreaRegionDO::getName, shortName + getSuffix(level));
            
            // 添加父级编码条件
            if (parentCode != null) {
                if (level == 2) {
                    wrapper.eq(AreaRegionDO::getProvCode, parentCode);
                } else if (level == 3) {
                    wrapper.eq(AreaRegionDO::getCityCode, parentCode);
                }
            }
            
            regions = areaRegionMapper.selectList(wrapper);
            if (!regions.isEmpty()) {
                return regions.get(0);
            }
        }
        
        return null;
    }

    /**
     * 根据名称和级别查找地区（不指定父级）
     */
    private AreaRegionDO findRegionByName(String name, int level) {
        return findRegionByName(name, level, null);
    }

    /**
     * 获取地区名称的简称（去掉省、市、区等后缀）
     */
    private String getShortName(String name) {
        if (!StringUtils.hasText(name)) {
            return name;
        }
        
        String[] suffixes = {"省", "市", "区", "县", "自治区", "特别行政区", "自治州", "地区", "盟"};
        for (String suffix : suffixes) {
            if (name.endsWith(suffix)) {
                return name.substring(0, name.length() - suffix.length());
            }
        }
        
        return name;
    }

    /**
     * 根据级别获取对应的后缀
     */
    private String getSuffix(int level) {
        switch (level) {
            case 1: return "省";
            case 2: return "市";
            case 3: return "区";
            default: return "";
        }
    }
}
